import { interceptor } from './require.js'; 
const tool = {
	// 请求
	getData(url,data,method,_this){
		/* uni.showLoading({
			title:'加载中...'
		}) */
		// interceptor();
		return new Promise((resolve,reject)=>{
			uni.request({
				url:getApp().globalData.domain + (uni.getStorageSync('identify') == '1'?'api.php/':'store.php/') + url,
				data:data,
				method:method?'GET':'POST',
				header: {
					token:uni.getStorageSync('uToken')?uni.getStorageSync('uToken'):'',
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				success: (res) => {
					// console.log('请求结果');
					// console.log(res);
					if(res.data.code == 200){
						resolve(res.data.data);
					}else if(res.data.code == 400){
						uni.removeStorageSync('userId');
						uni.removeStorageSync('storeId');
						uni.setStorageSync('identify','1');
						uni.switchTab({
							url:'/pages/home'
						})
					}else{
						uni.showToast({
							title:res.data.message,
							icon:"none"
						})
						resolve(false);
					}
				},
				fail:(err)=>{
					uni.hideLoading();
					console.log(err);
				}
			})
		})
	},
	// 用户上传图片
	upImg(file){
		uni.showLoading({
			title: '上传中...'
		})
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: getApp().globalData.domain + (uni.getStorageSync('identify') == '1'?'api.php/':'store.php/') + "User/uploadImage",
				filePath:file,
				name:'image',
				formData: {
				  token:uni.getStorageSync('uToken')?uni.getStorageSync('uToken'):'',
				},
				success:(res)=>{
					uni.hideLoading();
					res = JSON.parse(res.data);
					console.log(res);
					if (res.code == 200) {
						resolve(res.data);
					} else {
						resolve(false);
						uni.showToast({
							title:res.msg,
							icon:"none"
						})
					}
				},
				fail:(err)=>{
					uni.hideLoading();
					console.log(err);
					uni.showToast({
						title:'图片上传失败',
						icon:"none"
					})
				}
			})
		})
	},
	// 上传云店图片
	upImgs(file){
		uni.showLoading({
			title: '上传中...'
		})
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: getApp().globalData.domain +"api.php/User/uploadYunImage",
				filePath:file,
				name:'image',
				formData: {
				  token:uni.getStorageSync('uToken')?uni.getStorageSync('uToken'):'',
				},
				success:(res)=>{
					uni.hideLoading();
					res = JSON.parse(res.data);
					console.log(res);
					if (res.code == 200) {
						resolve(res.data);
					} else {
						resolve(false);
						uni.showToast({
							title:res.msg,
							icon:"none"
						})
					}
				},
				fail:(err)=>{
					uni.hideLoading();
					console.log(err);
					uni.showToast({
						title:'图片上传失败',
						icon:"none"
					})
				}
			})
		})
	},
	// 用户信息
	getUserInfo(){
		return tool.getData('User/index',{
			device:getApp().globalData.platform,
			// #ifdef MP-WEIXIN
			platform:'mini',
			// #endif
			// #ifdef APP-PLUS
			platform:'APP',
			// #endif
			memberId:uni.getStorageSync('userId')?uni.getStorageSync('userId'):'',
		}).then(res=>{
			return res;
		}).catch(err=>{
			console.log(err);
		})
	},
	// 员工信息
	getStaffInfo(){
		return tool.getData('User/index',{
			storeId:uni.getStorageSync('storeId')?uni.getStorageSync('storeId'):'',
		}).then(res=>{
			return res
		}).catch(err=>{
			console.log(err);
		})
	},
	// 获取下标
	getIdx(arr,sx,val){
		let idx = arr.findIndex((line)=>{
			return line[sx] == val;
		})
		return idx!=-1?idx:'-1';
	},
	// 获取下标2
	getIdx2(arr,sx,val){
		for(let i = arr.length - 1; i >= 0; i--){
		    if(arr[i][sx] == val){
				return i;
			}
	    }
	    return -1;
	},
	// 排序
	sortBy(props,status) {
		if(status == '1'){//大到小
			return function(a,b) {
			    return b[props] - a[props];
			}
		}else{//小到大
			return function(a,b) {
			    return a[props] - b[props];
			}
		}
	},
	// 时间戳转具体时间
	timestampToTime(timestamp,status){
	    let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	    let Y = date.getFullYear() + '-';
	    let M =(date.getMonth() + 1 < 10 ?'0' + (date.getMonth() + 1) :date.getMonth() + 1) + '-';
	    let D =(date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
	    let h =(date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	    let m =(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +':';
	    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
		if(status){
			return M + D + h + m + s;
		}else{
			return Y + M + D + h + m + s;
		}
	},
	// 监听分享动作
	monitor(link){
		if(uni.getStorageSync('uToken')){
			let curPage = getCurrentPages();
			uni.request({
				url:getApp().globalData.domain + '/api/sell/doShare',
				data:{
					action:'0',
					side:'0',
					page:curPage[curPage.length - 1].route,
					link:link?link:curPage[curPage.length - 1].route,
				},
				method:'POST',
				header: {
					token:uni.getStorageSync('uToken')?uni.getStorageSync('uToken'):'',
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				success: (res) => {
					console.log(res);	
				},
				fail:(err)=>{
					uni.hideLoading();
					console.log(err);
				}
			})
		}
	},
	// Object 转 url 参数
	objToUrl(obj){
		let url = '';
		Object.keys(obj).map((key)=>{
			url+=key+'='+obj[key]+'&';
		})
		url = url.slice(0,url.length-1);
		return url;
	},
	base64Save(base64File) { //base64File 需要加前缀
		const fsm = wx.getFileSystemManager(); //获取全局文件管理器
		let extName = base64File.match(/data\:\S+\/(\S+);/)
		if (extName) {
			//获取文件后缀
			extName = extName[1];
		}
		//获取自1970到现在的毫秒 + 文件后缀 生成文件名
		let fileName = Date.now() + '.' + extName
		return new Promise((resolve, reject) => {
			//写入文件的路径
			let filePath = wx.env.USER_DATA_PATH + '/' + fileName
			fsm.writeFile({
				filePath,
				data: base64File.replace(/^data:\S+\/\S+;base64,/, ''), //替换前缀为空
				encoding: 'base64',
				success: (res) => {
					resolve(filePath);
				},
				fail() {
					reject('写入失败');
				},
			});
		});
	},
	circleImgOne(ctx, img, x, y, r,status) {
	    ctx.save();
	    let d = r * 2;
	    let cx = x + r;
	    let cy = y + r;
	    ctx.arc(cx, cy, r+8, 0, 2 * Math.PI);
		if(status){
			ctx.fillStyle="#ffffff";//设置填充颜色
			ctx.fill();//开始填充
		}
	    ctx.strokeStyle = 'transparent'; // 设置绘制圆形边框的颜色
	    ctx.stroke(); // 绘制出圆形，默认为黑色，可通过 ctx.strokeStyle = '#FFFFFF'， 设置想要的颜色
	    ctx.clip();
	    ctx.drawImage(img, x, y, d, d);
	    ctx.restore();
	},
	canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
		if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
			return;
		}
		canvas.setFontSize(12) // 字号
		canvas.setFillStyle('#ffffff') // 字体颜色
		// 字符分隔为数组
		var arrText = text.split('');
		var line = '';
		var rowNum = 1
		for (var n = 0; n < arrText.length; n++) {
			var testLine = line + arrText[n];
			var metrics = canvas.measureText(testLine);
			var testWidth = metrics.width;
			if (testWidth > maxWidth && n > 0) {
				if (rowNum >= maxRowNum) {
					var arrLine = testLine.split('')
					// arrLine.splice(-9);
					var newTestLine = arrLine.join("")
					newTestLine += "...";
					
					canvas.fillText(newTestLine, x, y);
					return
				}
				canvas.fillText(line, x, y);
				line = arrText[n];
				y += lineHeight;
				rowNum += 1
			} else {
				line = testLine;
			}
		}
		canvas.fillText(line, x, y);
		return rowNum;
	},
	canvasWraptitleText2(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
		if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
			return;
		}
		// canvas.setFontSize(12); // 字号
		canvas.setFillStyle('#000000'); // 字体颜色
		canvas.font='normal bold 16px 微软雅黑';
		// 字符分隔为数组
		var arrText = text.split('');
		var line = '';
		var rowNum = 1
		for (var n = 0; n < arrText.length; n++) {
			var testLine = line + arrText[n];
			var metrics = canvas.measureText(testLine);
			var testWidth = metrics.width;
			if (testWidth > maxWidth && n > 0) {
				if (rowNum >= maxRowNum) {
					var arrLine = testLine.split('');
					// arrLine.splice(-9);
					var newTestLine = arrLine.join("");
					newTestLine = newTestLine.substring(0,17);
					newTestLine += "...";
					canvas.fillText(newTestLine, x, y);
					return rowNum
				}
				canvas.fillText(line, x, y);
				line = arrText[n];
				y += lineHeight;
				rowNum += 1
			} else {
				line = testLine;
			}
		}
		canvas.fillText(line, x, y);
		return rowNum;
	},
	back(){
		uni.navigateBack({
			delta:1
		})
	}
}
export default tool;